package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.params.RedMainResponseParams;
import com.foolishbird.sdk.params.ResponseParams;
import com.foolishbird.sdk.params.bean.RedCash;
import com.foolishbird.sdk.params.bean.RedEntrance;
import com.foolishbird.sdk.params.bean.RedUserInfo;
import com.foolishbird.sdk.params.bean.State;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;
import com.foolishbird.sdk.ui.view.ScollRedTextView;
import com.foolishbird.sdk.ui.view.ScrollListview;
import com.foolishbird.sdk.utils.MyFragmentManger;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.WL;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


public class RedPackageMainFragment extends BaseHttpFragment implements View.OnClickListener {


    private ScrollListview mListview;
    private TextView accountText,nameText,levelText,timeText,moneyText,detailText,tixianText,getRedPackageText,levelRedpackageText;
    private Button confirmBtn;
    private TextView titleTxt;
    private ImageView backView,avatarImage;
    private ScollRedTextView scollTextView;
    private MyAdapter myAdapter;

    public static final RedPackageMainFragment newInstance(Bundle bundle) {
        RedPackageMainFragment fragment = new RedPackageMainFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        int resource = ResUtils.getLayoutIdentifier(getActivity(), "fb_fragment_redpackage_main");
        View contentView =inflater.inflate(resource,null);
        backView = contentView.findViewById(getViewIdentifier("fb_fragment_login_back"));
        backView.setOnClickListener(this);
//        titleTxt = contentView.findViewById(getViewIdentifier("fb_fragment_float_title"));
//        titleTxt.setText("游戏开服");
//        mListview = contentView.findViewById(getViewIdentifier("float_notice_list"));
        avatarImage = contentView.findViewById(getViewIdentifier("redpackage_main_avatar"));
        accountText = contentView.findViewById(getViewIdentifier("redpackage_main_account"));
        nameText = contentView.findViewById(getViewIdentifier("redpackage_main_name"));
        levelText = contentView.findViewById(getViewIdentifier("redpackage_main_level"));
        timeText = contentView.findViewById(getViewIdentifier("redpackage_main_time"));
        moneyText = contentView.findViewById(getViewIdentifier("redpackage_main_money"));
        detailText = contentView.findViewById(getViewIdentifier("redpackage_main_detail"));
        detailText.setOnClickListener(this);
        tixianText = contentView.findViewById(getViewIdentifier("redpackage_main_tixian"));
        tixianText.setOnClickListener(this);
        getRedPackageText = contentView.findViewById(getViewIdentifier("redpackage_main_getredpackage"));
        getRedPackageText.setOnClickListener(this);
        levelRedpackageText = contentView.findViewById(getViewIdentifier("redpackage_main_levelredpackage"));
        levelRedpackageText.setOnClickListener(this);
        mListview = contentView.findViewById(getViewIdentifier("float_notice_list"));
        confirmBtn = contentView.findViewById(getViewIdentifier("redpackage_main_btn"));
        confirmBtn.setOnClickListener(this);
        scollTextView = contentView.findViewById(getViewIdentifier("redpackage_main_scrollText"));
        myAdapter = new MyAdapter(null);
        mListview.setAdapter(myAdapter);
        HttpEngineApi.getInstance().redpackageMain(requestCallbackHandler(RedMainResponseParams.class));
        return contentView;

    }

    private RedMainResponseParams.RedMainResponseData myData;

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (response != null) {
            int code = response.getState().getCode();
            if (State.SUCCESS == code) {
                if(response instanceof RedMainResponseParams){
                    myData =((RedMainResponseParams)response).getData();
                    setView();
                }
            }
//            setAdapter();
        }
        WL.d("FloatNoticeFragment",response.toString());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            HttpEngineApi.getInstance().redpackageMain(requestCallbackHandler(RedMainResponseParams.class));
        }
    }

    private void setView(){
        RedEntrance entrance = myData.getEntrance();
        if(entrance.getCashRedEntrance()==1){
            ((LinearLayout)getRedPackageText.getParent()).setVisibility(View.GONE);
        }else {
            ((LinearLayout)getRedPackageText.getParent()).setVisibility(View.VISIBLE);
        }
        if(entrance.getNormalRedEntrance()==1){
            ((LinearLayout)levelRedpackageText.getParent()).setVisibility(View.GONE);
        }else {
            ((LinearLayout)levelRedpackageText.getParent()).setVisibility(View.VISIBLE);
        }
        if(entrance.getSendRedEntrance()==1){
            confirmBtn.setVisibility(View.GONE);
        }else {
            confirmBtn.setVisibility(View.VISIBLE);
        }

        RedUserInfo userInfo = myData.getUserinfo();
        Picasso.with(getContext()).load(userInfo.getAvatar()).transform(new CircleTransform()).into(avatarImage);
        accountText.setText(userInfo.getName());
        nameText.setText(userInfo.getRoleName());
        levelText.setText(userInfo.getRoleLevel()+"级");
        timeText.setText("("+userInfo.getRoleCreated()+")");
        moneyText.setText(userInfo.getBalance()+"元");
//        RedCash cash =new RedCash();
//        cash.setCreatedAt("09-06 18:35:46");
//        cash.setAmount("23.23");
//        cash.setPrefixTitle("恭喜玩家【lcm***893】获得现金红包");
//        cash.setSuffixTitle("元");
//
//        RedCash cash2 =new RedCash();
//        cash2.setAmount("4.44");
//        cash2.setCreatedAt("09-06 18:35:46");
//        cash2.setPrefixTitle("恭喜玩家【ttttt】获得现金红包");
//        cash2.setSuffixTitle("元");
        List<RedCash> cashes=new ArrayList<>();
//        cashes.add(cash);
//        cashes.add(cash2);
        scollTextView.setData(myData.getRedNews());
        myAdapter.setCashs(myData.getRedCash());
    }



    class ViewHolder {
        TextView timeText;
        TextView prefixText;
        TextView moneyText;
        TextView suffixText;
    }



    @Override
    public void onClick(View view) {
        if(view ==backView){
            MyFragmentManger.getInstance().goBack(this);
        }else if (view == getRedPackageText){
//            MyFragmentManger.getInstance().gotoFragment(RedpackageSendFragment.newInstance(null));
            MyFragmentManger.getInstance().gotoFragment(RedpackageGetFragment.newInstance(null));
        }else if(view == confirmBtn){
            Bundle bundle = new Bundle();
            bundle.putSerializable("config",myData.getRedConfig());
            MyFragmentManger.getInstance().gotoFragment(RedpackageSendFragment.newInstance(bundle));
        }else if(view == detailText){
            MyFragmentManger.getInstance().gotoFragment(RedpackageDetailFragment.newInstance(null));
        }else if (view ==tixianText){
            Bundle bundle = new Bundle();
            bundle.putSerializable("config",myData.getRedConfig());
            MyFragmentManger.getInstance().gotoFragment(RedPackageTixianFragment.newInstance(bundle));
        }
//        OnFinishActivityListener listener = getOnFinishActivityListener();
//        if (listener != null) {
//            listener.doFinishActivity(this);
//        }
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }

    class CircleTransform implements Transformation {
        @Override
        public Bitmap transform(Bitmap source) {
            /**
             * 求出宽和高的哪个小
             */
            int  size = Math.min(source.getWidth(), source.getHeight());

            /**
             * 求中心点
             */
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;

            /**
             * 生成BitMap
             */
            Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
            if (squaredBitmap != source) {
                //释放
                source.recycle();
            }

            /**
             * 建立新的Bitmap
             */
            Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

            /**
             * 画布画笔
             */
            Canvas canvas = new Canvas(bitmap);
            Paint paint  = new Paint();

            BitmapShader shader = new BitmapShader(squaredBitmap,
                    BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
            paint.setShader(shader);
            paint.setAntiAlias(true);

            float r = size / 2f;
            /**
             * 画圆
             */
            canvas.drawCircle(r, r, r, paint);

            squaredBitmap.recycle();
            return bitmap;
        }

        @Override
        public String key() {
            return "circle";
        }
    }

    class MyAdapter extends BaseAdapter{

        private List<RedCash> cashs;
        public MyAdapter(List<RedCash> cashs){
            this.cashs = cashs;
        }

        public void setCashs(List<RedCash> cashs){
            this.cashs = cashs;
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            return cashs==null?0:cashs.size();
        }

        @Override
        public Object getItem(int i) {
            return cashs.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder = null;
            if (view == null) {
                int resource = ResUtils.getLayoutIdentifier(getContext(), "fb_redpackage_main_item");
                view = LayoutInflater.from(getContext()).inflate(resource, null);
                holder = new ViewHolder();
                holder.timeText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_main_item_time"));
                holder.prefixText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_main_item_prefix"));
                holder.moneyText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_main_item_money"));
                holder.suffixText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_main_item_suffix"));
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            RedCash menu =cashs.get(i);
            try {
                holder.timeText.setText(sdf2.format(sdf1.parse(menu.getCreatedAt())));
            }catch (Exception e){
                holder.timeText.setText(menu.getCreatedAt());
            }
//            holder.timeText.setText(menu.getCreatedAt());
            holder.prefixText.setText(menu.getPrefixTitle());
            holder.moneyText.setText(menu.getAmount());
            holder.suffixText.setText(menu.getSuffixTitle());
            return view;
        }
    }
    SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf2=new SimpleDateFormat("MM-dd HH:mm:ss");
}
